/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.common.configuration;

import com.inspur.edp.lcm.metadata.api.ConfigData.MetadataConfiguration;
import com.inspur.edp.lcm.metadata.common.ServiceUtils;
import com.inspur.edp.metadata.rtcustomization.api.exception.LcmConfigResolveException;
import com.inspur.edp.metadata.rtcustomization.api.exception.ErrorCodes;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;

/**
 * 元数据配置加载器
 * @author zhongchq
 * @since 1.0
 */
public class MetadataConfigurationLoader {

	@Setter
	@Getter
	public static List<MetadataConfiguration> metadataConfigurations;
	private static final String FILE_NAME = "config/platform/common/lcm_metadataextend.json";
	private static final String SECTION_NAME = "MetadataConfiguration";
	private String absoluteFilePath;
	public String getAbsoluteFilePath() {
		if (StringUtils.isEmpty(absoluteFilePath)) {
			absoluteFilePath = ServiceUtils.getAbsoluteConfigFilePath(FILE_NAME);
		}
		return absoluteFilePath;
	}

	/**
	 * @param
	 * @return java.util.List<com.inspur.gsp.lcm.metadata.entity.MetadataConfiguration>
	 * @throws
	 * @author zhongchq
	 * @description 类初始化时反序列化Json到实体
	 * @date 15:40 2019/7/23
	 **/
	protected List<MetadataConfiguration> loadMetadataConfigurations() {
		try {
			if (CollectionUtils.isEmpty(metadataConfigurations)) {
				metadataConfigurations = MetadataServiceHelper.getConfigurationList(getAbsoluteFilePath(), SECTION_NAME, MetadataConfiguration.class);
			}
			return metadataConfigurations;
		} catch (IOException e) {
			throw new LcmConfigResolveException(e, ErrorCodes.ECP_CONFIG_RESOLVE_0002, getAbsoluteFilePath());
		}
	}

	protected MetadataConfiguration getMetadataConfigurationData(String typeName) {
		loadMetadataConfigurations();
		if (metadataConfigurations != null && metadataConfigurations.size() > 0) {
			for (MetadataConfiguration data : metadataConfigurations) {
				if (data.getCommon().getTypeCode().equalsIgnoreCase(typeName)) {
					return data;
				}
			}
		}
		return null;
	}
}
